package com.maori.languageapp.curate.word;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.maori.languageapp.LanguageAppCaptureModify;
import com.maori.languageapp.R;
import com.maori.languageapp.consts.ImageLoader;
import com.maori.languageapp.discover.word.Maori_Discover_Word_Details;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class Maori_Curate_Word_Details_Adapter extends BaseAdapter {
	private static final String TAG = null;
	// Declare Variables
	Context context;
	LayoutInflater inflater;
	ArrayList<HashMap<String, String>> data;
	ImageLoader imageLoader;
	String SYNUserLikedSyn,TotalsSetDefault,UserCurateStateSynonim,MContent, EContent;
	/*Button setModifyAction;
	Button setApproveAction;*/
	int timeoutConnection = 5000;
	int TotalLikesVal;
	HttpParams httpParameters = new BasicHttpParams();
	String SynUserID, SynNodeId, SynParentNodeId,
			SynMediaType;
	private LayoutInflater mInflater;
	InputStream is = null;
	StringBuilder sb = null;
	String result, CurrentUserID,TotalLikes,SYNParentUID,NodeMediaCode,NodeApproveCount,NodeRejectCount;
	int LikeActive = 0;
	int LikeCounter;
	ArrayList<HashMap<String, String>> arraylist;
	JSONArray jsonarray;
	HashMap<String, String> resultp = new HashMap<String, String>();
	
	
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	private String LIKESLOG = "LikesLog";

	public Maori_Curate_Word_Details_Adapter(Context context,
			ArrayList<HashMap<String, String>> arraylist) {
		this.context = context;
		data = arraylist;
		imageLoader = new ImageLoader(context);
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		 return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		 return position;
	}
	
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		// Declare Variables
		 if (convertView == null) {
		        convertView = mInflater.inflate(R.layout.languageapp_curate_synonyms, null);
		        holder = new ViewHolder();
		        holder.maori_synonym_title = (TextView) convertView.findViewById(R.id.maori_synonym_title);
		        holder.maori_synonym_title = (TextView) convertView.findViewById(R.id.maori_synonym_title);
				holder.english_synonym_title = (TextView) convertView.findViewById(R.id.english_synonym_title);
				holder.dicover_location = (Button) convertView.findViewById(R.id.dicover_location);
				holder.display_dialect = (Button) convertView.findViewById(R.id.display_dialect);
				holder.first_name = (TextView) convertView.findViewById(R.id.first_name);
				holder.last_name = (TextView) convertView.findViewById(R.id.last_name);
				holder.flag = (ImageView) convertView.findViewById(R.id.imggriditem);
				holder.setModifyAction = (Button) convertView.findViewById(R.id.setModifyAction);
				holder.setRejectAction = (Button) convertView.findViewById(R.id.setRejectAction);
				holder.setApproveAction = (Button) convertView.findViewById(R.id.setApproveAction);
		        convertView.setTag(holder);
		    } else {
		        holder = (ViewHolder) convertView.getTag();
		    }


		resultp = data.get(position);


		// Capture position and set results to the TextViews
		holder.maori_synonym_title.setText(resultp.get(Maori_Curate_Word_Details.getDescription_a()));
		holder.english_synonym_title.setText(resultp.get(Maori_Curate_Word_Details.getDescription_b()));
		holder.dicover_location.setText(resultp.get(Maori_Curate_Word_Details.getSYNcurrent_location()));
		holder.display_dialect.setText(resultp.get(Maori_Curate_Word_Details.getSYNdialact()));// SYNtribe
		holder.first_name.setText(resultp.get(Maori_Curate_Word_Details.getFirst_namesuser()) + " " + resultp.get(Maori_Curate_Word_Details.getLast_nameuser()));
		holder.last_name.setText(resultp.get(Maori_Curate_Word_Details.getSYNtribe()));
		String UIDuser = resultp.get(Maori_Curate_Word_Details.getUIDuser());
		String SYNNID = resultp.get(Maori_Curate_Word_Details.getSYNNID());
		String SYNParentNID = resultp.get(Maori_Curate_Word_Details.getSYNParentNID());
		
		MContent = resultp.get(Maori_Curate_Word_Details.getDescription_a());
		EContent = resultp.get(Maori_Curate_Word_Details.getDescription_b());
		
		SYNUserLikedSyn = resultp.get(Maori_Curate_Word_Details.getSYNUserLikedSyn());
		TotalLikes = resultp.get(Maori_Curate_Word_Details.getTotalsLikesSyn());
		CurrentUserID = resultp.get(Maori_Curate_Word_Details.getSYNParentUID());
		TotalsSetDefault = resultp.get(Maori_Curate_Word_Details.getTotalsSetDefault());
		NodeMediaCode = resultp.get(Maori_Curate_Word_Details.getNodeMediaCode());
		
		UserCurateStateSynonim = resultp.get(Maori_Curate_Word_Details.getUserCurateStateSynonim());
		Log.e("TAG ", "XXXX 1 : " + UserCurateStateSynonim);
		imageLoader.DisplayImage(resultp.get(Maori_Discover_Word_Details.getUserimageuser()), holder.flag);

		/*****************Curate Approve Reject Count***************************/
		NodeApproveCount = resultp.get(Maori_Curate_Word_Details.getNodeApprovalCountValSynonim());
		NodeRejectCount = resultp.get(Maori_Curate_Word_Details.getNodeRejectedCountValSynonim());
		
		holder.setApproveAction.setText("Approve(" + NodeApproveCount + ")");
		holder.setRejectAction.setText("Reject(" + NodeRejectCount + ")");
		
		if(UserCurateStateSynonim.equals("1")){
			holder.setApproveAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_active, 0, 0, 0);
			holder.setApproveAction.setTextColor(Color.parseColor("#07afdf"));
			holder.setApproveAction.setEnabled(false);
		}
		else if(UserCurateStateSynonim.equals("2")){
			holder.setRejectAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_reject_active, 0, 0, 0);
			holder.setRejectAction.setEnabled(false);
			holder.setRejectAction.setTextColor(Color.parseColor("#07afdf"));
		}
		else if(UserCurateStateSynonim.equals("3")){
			holder.setModifyAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_modify_active, 0, 0, 0);
			holder.setModifyAction.setTextColor(Color.parseColor("#07afdf"));
			holder.setModifyAction.setEnabled(false);
		}
		
		holder.setApproveAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				resultp = data.get(position);
				SynUserID = resultp.get(Maori_Curate_Word_Details.getUIDuser());
				SynNodeId = resultp.get(Maori_Curate_Word_Details.getSYNNID());
				SynParentNodeId = resultp.get(Maori_Curate_Word_Details.getSYNParentNID());
				SynMediaType = "0";
				
				final Dialog dialog=new Dialog(context);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.languageapp_curate_approve_form);
				
				Button rejectaccept=(Button)dialog.findViewById(R.id.rejectaccept);
				rejectaccept.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {
						UserCurateStateSynonim = resultp.get(Maori_Curate_Word_Details.getUserCurateStateSynonim());
						NodeApproveCount = resultp.get(Maori_Curate_Word_Details.getNodeApprovalCountValSynonim());
						NodeRejectCount = resultp.get(Maori_Curate_Word_Details.getNodeRejectedCountValSynonim());
						int NodeRejectedCountVal = Integer.parseInt(NodeRejectCount); 
						int NodeApprovalCountVal = Integer.parseInt(NodeApproveCount);
						if(UserCurateStateSynonim.equals("2")){
							NodeRejectedCountVal = NodeRejectedCountVal - 1;
							NodeApprovalCountVal = NodeApprovalCountVal + 1;
							holder.setApproveAction.setText("Approve(" + NodeApprovalCountVal + ")");
							holder.setRejectAction.setText("Reject(" + NodeRejectedCountVal + ")");
						}
						else{
							NodeApprovalCountVal = NodeApprovalCountVal + 1;
							holder.setApproveAction.setText("Approve(" + NodeApprovalCountVal + ")");
							holder.setRejectAction.setText("Reject(" + NodeRejectedCountVal + ")");
						}
						
						//Update adapter counters
						UserCurateStateSynonim = "1";
						resultp.put("UserCurateStateSynonim", "1");
						resultp.put("NodeApprovalCountValSynonim", "" + NodeApprovalCountVal);
						resultp.put("NodeRejectedCountValSynonim", "" + NodeRejectedCountVal);
						
						holder.setApproveAction.setEnabled(false);
						holder.setApproveAction.setTextColor(Color.parseColor("#07afdf"));
						holder.setApproveAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_active, 0, 0, 0);
						
						holder.setRejectAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_reject_inactive, 0, 0, 0);
						holder.setRejectAction.setTextColor(Color.parseColor("#626262"));
						holder.setRejectAction.setEnabled(true);
						holder.setModifyAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_modify_inactive, 0, 0, 0);
						holder.setModifyAction.setTextColor(Color.parseColor("#626262"));
						holder.setModifyAction.setEnabled(true);
						dialog.dismiss();
						new UploadApprovalInformation().execute();
					}
				});
				
				Button rejectcancel=(Button)dialog.findViewById(R.id.rejectcancel);
				rejectcancel.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {
						dialog.dismiss();
					}
				});
				dialog.show();
			}
		});
		
		
		holder.setRejectAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				resultp = data.get(position);
				SynUserID = resultp.get(Maori_Curate_Word_Details.getUIDuser());
				SynNodeId = resultp.get(Maori_Curate_Word_Details.getSYNNID());
				SynParentNodeId = resultp.get(Maori_Curate_Word_Details.getSYNParentNID());
				SynMediaType = "0";
				
				
				final Dialog dialog=new Dialog(context);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.languageapp_curate_reject_form);
				
				Button rejectaccept=(Button)dialog.findViewById(R.id.rejectaccept);
				rejectaccept.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {
						UserCurateStateSynonim = resultp.get(Maori_Curate_Word_Details.getUserCurateStateSynonim());
						NodeApproveCount = resultp.get(Maori_Curate_Word_Details.getNodeApprovalCountValSynonim());
						NodeRejectCount = resultp.get(Maori_Curate_Word_Details.getNodeRejectedCountValSynonim());
						int NodeRejectedCountVal = Integer.parseInt(NodeRejectCount); 
						int NodeApprovalCountVal = Integer.parseInt(NodeApproveCount);
						if(UserCurateStateSynonim.equals("1")){
							NodeRejectedCountVal = NodeRejectedCountVal + 1;
							NodeApprovalCountVal = NodeApprovalCountVal - 1;
							holder.setApproveAction.setText("Approve(" + NodeApprovalCountVal + ")");
							holder.setRejectAction.setText("Reject(" + NodeRejectedCountVal + ")");
						}
						else{
							NodeRejectedCountVal = NodeRejectedCountVal + 1;
							holder.setApproveAction.setText("Approve(" + NodeApprovalCountVal + ")");
							holder.setRejectAction.setText("Reject(" + NodeRejectedCountVal + ")");
						}
						
						//Update adapter counters
						UserCurateStateSynonim = "2";
						resultp.put("UserCurateStateSynonim", "2");
						resultp.put("NodeApprovalCountValSynonim", "" + NodeApprovalCountVal);
						resultp.put("NodeRejectedCountValSynonim", "" + NodeRejectedCountVal);
						
						
						
						holder.setRejectAction.setEnabled(false);
						holder.setRejectAction.setTextColor(Color.parseColor("#07afdf"));
						holder.setRejectAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_reject_active, 0, 0, 0);
						
						holder.setApproveAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_inactive, 0, 0, 0);
						holder.setApproveAction.setTextColor(Color.parseColor("#626262"));
						holder.setApproveAction.setEnabled(true);
						holder.setModifyAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_modify_inactive, 0, 0, 0);
						holder.setModifyAction.setTextColor(Color.parseColor("#626262"));
						holder.setModifyAction.setEnabled(true);
						dialog.dismiss();
						new UploadApprovalInformation().execute();
						
					}
				});
				
				Button rejectcancel=(Button)dialog.findViewById(R.id.rejectcancel);
				rejectcancel.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {
						dialog.dismiss();
					}
				});
				dialog.show();
			}
		});
		
		

		holder.setModifyAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent(context, LanguageAppCaptureModify.class);
				intent.putExtra("NCMID", NodeMediaCode);
				intent.putExtra("node_category", NodeMediaCode);
				intent.putExtra("type", "Word");
				intent.putExtra("SEARCHKEY", SynNodeId + "/00/00/" + MContent + "/" +EContent);
				intent.putExtra("ACTIVE", "1");
				context.startActivity(intent);
			}
		});
		
		
		
		
		return convertView;
	}
	static class ViewHolder {
		TextView maori_synonym_title;
		TextView english_synonym_title;
		TextView first_name; 
		TextView last_name;
		Button display_dialect;
		Button dicover_location;
		Button setRejectAction;
		Button setModifyAction;
		Button setApproveAction;
		ImageView flag;
	}
	/*********************CURATE**********************/
	
	
	private class UploadApprovalInformation extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();
				httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/curate/SaveCurateApprovalInfo.php");

				json.put("record1", CurrentUserID); // $approve_user
				json.put("record2", UserCurateStateSynonim); // $approve_state
				json.put("record3", SynNodeId); // $approve_node
				json.put("record4", "0"); // $approve_media
				json.put("record5", "0"); // $approve_media_id
	
//[{"record3":"29","record4":"0","record1":"6","record2":"0","record5":"0"}]

				
				
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.v("TAG","POST SET DEF : " + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					Log.v("TAG", "Print RES ***:" + result);
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			
		}
	}

}
